package gnssio

import (
	"dgo/goutils/utils"
	"sync/atomic"
	"time"
)

var (
	_ICY_200_OK string = "ICY 200 OK"
)

type CommMultiChannelSingle struct {
	startflag int32

	sn              int
	caption         string
	owner           *CommMultiChannel
	comm            I_Comm
	canStop         int
	connected       bool
	lastRecv        time.Time
	firstrecv       time.Time
	filterfirstrecv int
}

func NewChannelSingle(comm I_Comm) *CommMultiChannelSingle {
	rval := &CommMultiChannelSingle{
		comm:            comm,
		startflag:       0,
		filterfirstrecv: 0,
	}
	return rval
}

func (this *CommMultiChannelSingle) OnReceive(sender I_Comm, buf []byte, l int) {
	if this.filterfirstrecv == 1 {
		if this.firstrecv.IsZero() {
			this.firstrecv = time.Now()
			return // 过滤掉第一次收到的数据  ICY 200 OK / UN
		}
	}

	this.lastRecv = time.Now()
	this.owner.OnChannelRecv(this, buf[:l])
}

func (this *CommMultiChannelSingle) OnConnect(sender I_Comm) {
	this.owner.OnChannelConnect(this)
	this.canStop = 0
	this.connected = true
}

func (this *CommMultiChannelSingle) OnDisconnect(sender I_Comm) {
	this.owner.OnChannelDisconnect(this)
	this.canStop = 1
	this.connected = false
}

func (this *CommMultiChannelSingle) Stop() {
	if atomic.CompareAndSwapInt32(&this.startflag, 1, 0) {
		this.comm.Stop()
		for { // 等待关闭后再 移除
			if this.canStop == 1 {
				break
			}
			time.Sleep(time.Millisecond * 500)
		}
		this.comm.RemoveListener(this)
	}
}

func (this *CommMultiChannelSingle) CanUse(timeout time.Duration) bool {
	return this.connected && time.Now().Sub(this.lastRecv) < timeout
}

func (this *CommMultiChannelSingle) Start() {
	if atomic.CompareAndSwapInt32(&this.startflag, 0, 1) {
		this.comm.AddListener(this)
		this.comm.Start()
		utils.Log.Infof("[%d]%s", this.sn, this.caption)
	}
}

func (this *CommMultiChannelSingle) DoRelease() {
	this.owner = nil
	this.comm = nil

}
